//
//  Tool.m
//  ocCrazy
//
//  Created by mac on 2018/4/17.
//  Copyright © 2018年 dukai. All rights reserved.
//

#import "Tool.h"
#import <sys/utsname.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
#import "AppDelegate+Tool.h"

static Tool *_tool = nil;


NSString *IntToString(NSInteger num){
    return @(num).stringValue;
};

UIFont *FloatToFont(float font){
    return [UIFont systemFontOfSize:font];
}

float TrueFont(float font){
    float trueFont = font;
    if (YYScreenWidth() == 320) {
        trueFont = font - 1;
    }
    if (YYScreenWidth() == 414) {
        trueFont = font + 1;
    }
    return trueFont;
}
UIFont *TrueFloatToFont(float font){
    return [UIFont systemFontOfSize:TrueFont(font)];
}

@implementation Tool
{
    CTCallCenter *_center;
}

+ (instancetype)share{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _tool = [[Tool alloc] init];
    });
    return _tool;
}







+ (BOOL)CC_isX
{

   BOOL isPhoneX = NO;
   if (@available(iOS 11.0, *)) {
      isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;
   }
    return isPhoneX;
}

+ (CGFloat)cc_FrameForX:(CGFloat)f{
    if ([Tool CC_isX]) {
        return f + 34;
    }
    return f;
}
+ (CGFloat)cc_FrameForNavX:(CGFloat)f{
    
    if ([Tool CC_isX]) {
        return f + 24;
    }
    return f;
    
}


+ (void)showAlert:(NSString *)message vc:(UIViewController *)vc{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [vc presentViewController:alertVC animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    });
}


+ (void)showAlert:(NSString *)message{
        [Tool showAlert:message vc:[AppDelegate getCurrentVC]];
}

+ (void)showSheet:(NSArray<NSString *> *)messages withTitle:(NSString *)title withSuccess:(void(^)(NSString *message))success withCutomStyle:(NSArray <UIColor *>*(^)())styleBack{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:title preferredStyle:UIAlertControllerStyleActionSheet];
    NSArray <UIColor *>*arr = nil;
    if (styleBack() != nil) {
        arr = styleBack();
    }
    
    for (NSString *message in messages) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:message style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (success) {
                success(message);
            }
        }];
        
    
        if (arr) {
            NSInteger count = [messages indexOfObject:message];
            if (count >= arr.count) count = 0;
            [action setValue:arr[count] forKey:@"titleTextColor"];
        }
        [alertVC addAction:action];
    }
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:action];
    if (arr) [action setValue:arr.lastObject forKey:@"titleTextColor"];
    BaseViewController *vc = [AppDelegate getCurrentVC];
    [vc presentViewController:alertVC animated:YES completion:nil];
}
+ (void)saveImageToAlbum:(UIImage *)image withBlock:(nullable void(^)(BOOL success, NSError *__nullable error))block{

   

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            
            PHAssetChangeRequest *changeAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
           PHAssetCollection *_targetCollection = [self createdAssetCollection];
            
            PHAssetCollectionChangeRequest *changeCollectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:_targetCollection];
            
            
            
            PHObjectPlaceholder *assetPlaceholder = [changeAssetRequest placeholderForCreatedAsset];
            
            [changeCollectionRequest addAssets:@[assetPlaceholder]];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                block(success,error);
            });
        }];
    
}


+ (PHAssetCollection *)createdAssetCollection{
    
     PHFetchResult<PHAssetCollection *> * assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:@"易车网"]) {
            return assetCollection;
        }
    }
    
   __block NSError *error = nil;

    __block NSString *assetCollectionLocalIdentifier = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            
            assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"易车网"].placeholderForCreatedAssetCollection.localIdentifier;
            
        } error:&error];
    });
   
  
    
    if (error) return nil;
    
    PHAssetCollection *assetCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[@"易车网"] options:nil].lastObject;
    
    return assetCollection;
    
}



+ (void)getCityCenterCoordinatewithCityName:(NSString *)cityName withBlock:(void(^)(CLLocationCoordinate2D centerCoordinate,NSError *error))block {
//  
//    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
//    [myGeocoder geocodeAddressString:cityName completionHandler:^(NSArray *placemarks, NSError *error) {
//        if ([placemarks count] > 0 && error == nil) {
//            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
//            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
//            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
//            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
//            dispatch_async(dispatch_get_main_queue(), ^{
//            block(firstPlacemark.location.coordinate,nil);
//            });
//        }
//        else if ([placemarks count] == 0 && error == nil) {
//            NSError *aError = [[NSError alloc] init];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                block(CLLocationCoordinate2DNew(),aError);
//            });
//        } else if (error != nil) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                block(CLLocationCoordinate2DNew(),error);
//            });
//        }
//    }];
}

+ (CLLocationCoordinate2D)getCityCoordinate{
    double longitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"] doubleValue];
    double latitude = [[[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"] doubleValue];
    return CLLocationCoordinate2DMake(latitude, longitude);
}

+ (void)getCityDetail{
//    [CrazyLocation startUpdataUserLocation:^(double longitude, double latitude) {
//        if (longitude == 0 && latitude == 0) {
//            [JKToast showWithText:@"定位失败,请重试"];
//        }else{
//            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:longitude] forKey:@"longitude"];
//            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:latitude] forKey:@"latitude"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
//    } cityBlock:^(NSDictionary *addressDic) {
//        if (addressDic) {
//            [[NSUserDefaults standardUserDefaults] setObject:addressDic forKey:@"myCity"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
//    }];
}

+ (void)phone:(NSString *)phoneNum{
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", phoneNum];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
    Tool *tool = [Tool share];
   tool->_center = [[CTCallCenter alloc] init];
   tool->_center.callEventHandler = ^(CTCall *call) {
        if ([call.callState isEqualToString:@"CTCallStateDialing"]) {
            NSLog(@"打电话了");
            
        }
   };
}



+(BOOL)isHaveEmptyString:(NSString *) string {
    
    NSRange range = [string rangeOfString:@" "];
    
    if (range.location != NSNotFound) {
        return YES;
    }
    else {
        return NO;
    }
    
}



+ (void)test:(NSString *)json{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [webView loadHTMLString:json baseURL:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:webView];
}

+ (BOOL)isChinese:(NSString *)str
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

//数字验证
+(BOOL)ValidateNumber:(NSString *)Number{
    NSString *emailRegex = @"^[0-9]*$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:Number];
    
}
//车牌号验证
+ (BOOL) ValidateCarNo:(NSString *)Number{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:Number];
}
#pragma mark -判断字符串为空
+ (BOOL) isBlankString:(NSString *)aStr {
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!aStr.length) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}
+ (BOOL)isPhone:(NSString *)str
{
    NSString *regex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", regex];
    return [predicate evaluateWithObject:str];
}

+(BOOL)checkCarID:(NSString *)carID;
{
    if (carID.length==7) {
        //普通汽车，7位字符，不包含I和O，避免与数字1和0混淆
        NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-hj-np-zA-HJ-NP-Z]{1}[a-hj-np-zA-HJ-NP-Z0-9]{4}[a-hj-np-zA-HJ-NP-Z0-9\u4e00-\u9fa5]$";
        NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
        return [carTest evaluateWithObject:carID];
    }else if(carID.length==8){
        //新能源车,8位字符，第一位：省份简称（1位汉字），第二位：发牌机关代号（1位字母）;
        //小型车，第三位：只能用字母D或字母F，第四位：字母或者数字，后四位：必须使用数字;([DF][A-HJ-NP-Z0-9][0-9]{4})
        //大型车3-7位：必须使用数字，后一位：只能用字母D或字母F。([0-9]{5}[DF])
        NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-hj-np-zA-HJ-NP-Z]{1}([0-9]{5}[d|f|D|F]|[d|f|D|F][a-hj-np-zA-HJ-NP-Z0-9][0-9]{4})$";
        NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
        return [carTest evaluateWithObject:carID];
    }
    return NO;
}


@end
